#include"comm.hpp"

int main()
{
    //获取key
    Log("child pid is : ",Debuge)<<getpid()<<endl;
    key_t k = ftok(PATH_NAME, PROJ_ID);
    if(k<0)
    {
        Log("creat key failed",Error)<<" client key : "<<k<<endl;
        exit(1);
    }
    Log("creat key done",Debuge)<<" client key : "<<k<<endl;

    //获取共享内存
    int shmid = shmget(k,SHM_SIZE,0);
    if(shmid<0)
    {
        Log("creat shm failed",Error)<<" client key : "<<k<<endl;
        exit(2);
    }
    Log("create shm sucess", Debuge) << " client key : " << k << endl;
   // sleep(10);
    //挂接共享内存
    char *shmaddr = (char *)shmat(shmid, nullptr, 0);
    if(shmaddr==nullptr)
    {
        Log("attach shm failed",Error)<<" client key : "<<k<<endl;
        exit(3);
    }
    Log("attach shm sucess", Debuge) << " client key : " << k << endl;
    //sleep(10);
    //使用
    //client对共享内存进行写入操作
    // char a= 'a';
    // for(;a<'d';a++)
    // {
    //     snprintf(shmaddr,SHM_SIZE-1,"hello server,我是其他进程，我的pid：%d,inc:%c\n",getpid(),a);
    //     sleep(2);
    // }
    int fd = OpenFIFO(FIFO_NAME,WRITE);
    while(true)
    {
        
        ssize_t s = read(0,shmaddr,SHM_SIZE-1 );
        if(s>0)
        {
            shmaddr[s-1]=0;
            Signal(fd);//写完之后唤醒读取端
            if(strcmp(shmaddr,"quit")==0) break;
        }
    }
    CloseFIFO(fd);
    //strcpy(shmaddr,"quit");

    //用管道进行共享内存的访问控制

    //去关联
    int dt = shmdt(shmaddr);
    assert(dt != -1);
    (void)dt;
    Log("detach shm success", Debuge) << " client key : " << k << endl;
   // sleep(10);
    return 0;
}